package com.away.transaction;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;


/**
 * 保存订单服务
 */
@Service
public class OrderTransactionService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送半消息到broker
     * @return
     */
    public String saveOrder(String orderId,String orderInfo){
        JSONObject msgJ = new JSONObject();
        msgJ.put("orderId", orderId);
        msgJ.put("goodsInfo", "商品信息");
        MessageBuilder<String> smb = MessageBuilder.withPayload(msgJ.toJSONString());//用来发送给消费者消息的序列话对象
        smb.setHeader("orderId", orderId);//用于在本地事务进行操作的对象
        smb.setHeader("orderInfo", orderInfo);//用于在本地事务进行操作的对象
        Message<String> build = smb.build();
        //这个先把消息异步发送给broker，然后再调用 RocketMQLocalTransactionListener.executeLocalTransaction
        rocketMQTemplate.sendMessageInTransaction("transactionGroup","test_transaction_topic",build,"");
        return orderId;
    }
}
